﻿function getGeoInfo(address) {
   
}
function initBigMap(addresses, crnt) {
	geocoder = new google.maps.Geocoder();
	geocoder.geocode( { 'address': addresses[crnt]}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			var mapOptions = {
				center: results[0].geometry.location,
				zoom: 12,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};
			var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
			for (var key in addresses) {
				(function(){
			        var n = parseInt(key);
				    var val = addresses [key];
				    geocoder.geocode( { 'address': val}, function(results, status) {
				        if (status == google.maps.GeocoderStatus.OK) {
				        	var contentString = '<div class="map_popup">'+
										        	'<div class="object-img"><img style="width:200px;" src="'+window.images[n]+'"/></div>'+
										        	'<div class="object-price">'+window.prices[n]+' €</div>'+
										            '<a target="_blank" href="'+window.urls[n]+'" title="'+window.names[n]+'">'+window.names[n]+'</a>'+
									            '</div>';
				        	var infowindow = new google.maps.InfoWindow({
				                content: contentString
				            });
				        	var img = n!=crnt ? '/images/map_icon.png' : '/images/map_icon_a.png'
				        	//var houseMarkerShadow = new google.maps.MarkerImage(img, new google.maps.Size(37, 32), new google.maps.Point(0,0), new google.maps.Point(0, 32));
						    var marker = new google.maps.Marker({
					    		map: map,
					    		position: results[0].geometry.location,
					    		icon: img,
					    		title: val,
					    		zIndex: n!=crnt ? 1 : 2,
			    				clickable: true,
			    				//shadow:houseMarkerShadow
					    	});
						    google.maps.event.addListener(marker, 'click', function() {
						    	infowindow.close();
						    	infowindow.open(map, marker);
						    	this.setOptions({icon: '/images/map_icon_a.png'});
				            });
						    google.maps.event.addListener(map, 'click', function() {
						    	infowindow.close();
						    	marker.setOptions({icon: '/images/map_icon.png'});
						      });
						    google.maps.event.addListener(infowindow,'closeclick',function(){
						    	marker.setOptions({icon: '/images/map_icon.png'});
					    	});
						    google.maps.event.addListener(marker, 'mouseover', function () {
				                this.setOptions({zIndex:2});
				            });
				            google.maps.event.addListener(marker, 'mouseout', function () {
				                this.setOptions({zIndex:1});
				            });
						    //if(n==crnt) infowindow.open(map,marker);
				        } else {
				      	  alert("Geocode was not successful for the following reason: " + status);
				        }
			    	});
			    //end scope block
			    })();
			}
		} else {
			alert("Geocode was not successful for the following reason: " + status);
		}
	});
}
function initMap(address) {
	geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var mapOptions = {
    		center: results[0].geometry.location,
    		zoom: 12,
    		mapTypeId: google.maps.MapTypeId.ROADMAP
    	};
    	var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    	var marker = new google.maps.Marker({
    		map: map,
    		position: results[0].geometry.location,
    		icon: '/images/map_icon.png',
    		title: address
    	});
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
}
function initMapStreeView(address) {
	geocoder = new google.maps.Geocoder();
	geocoder.geocode( { 'address': address}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			var panoramaOptions = {
			  position: results[0].geometry.location,
			  pov: {
			    heading: 34,
			    pitch: 10
			  }
			};
			var map = new google.maps.Map(document.getElementById("map_streetview"));
			var panorama = new  google.maps.StreetViewPanorama(document.getElementById("map_streetview"), panoramaOptions);
			map.setStreetView(panorama);
		} else {
			alert("Geocode was not successful for the following reason: " + status);
		}
	});
}
	
$.fn.slideFadeToggle = function(speed, easing, callback){
	return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);
};

$(document).ready(function() {
	$('.catalog-filter h3').click(function(){
		$(this).next('.filter_content').slideFadeToggle('slow');
	});
	$('#Users_image').change(function(){
		$(this).parents('form#user-upload').submit();
	});
	// trips
	$('#trips').live('click',function(){
		var id = $('#trips_all').attr('href');
		$.ajax({
			url: '/users/trips',
			dataType: "html",
			type: "GET",
			cache: false,
			success: function(data) {
				$('#trips_list li').slideFadeToggle('fast', function () {
					$.when( $('#trips_list').html(data) )
						.done( function(){
							$('#trips_list li').css('display','none');
							$('#trips_list li').slideFadeToggle('slow');
						});
			    });
			}
		});
		return false;
	});
	$('#trips_all').live('click',function(){
		var id = $('#trips_all').attr('href');
		$.ajax({
			url: '/users/alltrips',
			dataType: "html",
			type: "GET",
			cache: false,
			success: function(data) {
				$('#trips_list li').slideFadeToggle('fast', function () {
					$.when( $('#trips_list').html(data) )
						.done( function(){
							$('#trips_list li').css('display','none');
							$('#trips_list li').slideFadeToggle('slow');
						});
			    });
			}
		});
		return false;
	});
	$('#trips_old').live('click',function(){
		var id = $('#trips_all').attr('href');
		$.ajax({
			url: '/users/oldtrips',
			dataType: "html",
			type: "GET",
			cache: false,
			success: function(data) {
				$('#trips_list li').slideFadeToggle('fast', function () {
					$.when( $('#trips_list').html(data) )
						.done( function(){
							$('#trips_list li').css('display','none');
							$('#trips_list li').slideFadeToggle('slow');
						});
			    });
			}
		});
		return false;
	});

	// booking
	$('#booking_all').live('click',function(){
		var id = $('#booking_all').attr('href');
		$.ajax({
			url: '/users/allBooking?id=' + id,
			dataType: "html",
			type: "GET",
			cache: false,
			success: function(data) {
				$('#booking_list li').slideFadeToggle('fast', function () {
					$.when( $('#booking_list').html(data) )
						.done( function(){
							$('#booking_list li').css('display','none');
							$('#booking_list li').slideFadeToggle('slow');
						});
			    });
			}
		});
		return false;
	});
	$('#booking_new').live('click',function(){
		var id = $('#booking_new').attr('href');
		$.ajax({
			url: '/users/newBooking?id=' + id,
			dataType: "html",
			type: "GET",
			success: function(data) {
				$('#booking_list li').slideFadeToggle('fast', function () {
					$.when( $('#booking_list').html(data) )
						.done( function(){
							$('#booking_list li').css('display','none');
							$('#booking_list li').slideFadeToggle('slow');
						});
			    });
			}
		});
		return false;
	});
	$('#booking_old').live('click',function(){
		var id = $('#booking_old').attr('href');
		$.ajax({
			url: '/users/oldBooking?id=' + id,
			dataType: "html",
			type: "GET",
			success: function(data) {
				$('#booking_list li').slideFadeToggle('fast', function () {
					$.when( $('#booking_list').html(data) )
						.done( function(){
							$('#booking_list li').css('display','none');
							$('#booking_list li').slideFadeToggle('slow');
						});
			    });
			}
		});
		return false;
	});
	$('.destination').keyup(function(){
		var des = $(this).val();
		if(des.length>=3){
			$.ajax({
				url: '/cataloge/getDestination?string=' + $(this).val(),
				type: "GET",
				success: function(data) {
					//if(data.error === undefined){
					$('.destination_help').show(0).children('.variant').html(data);
					//}
				}
			});
		} else {
			$('.destination_help').hide(0).children('.variant').html('');
		}
	});
	$('.destination').click(function(){
		if($('.destination_help').find('ul li').length!=0){
			$('.destination_help').show(0);
		}
		return false;
	});
	$('.variant li').live('click',function(){
		$('.destination').val($(this).html());
		return false;
	});
	$('body').live('click',function(){
		$('.destination_help').hide(0);
	});
	// upload images
	$('#fileToUpload').live('change', function(){
		var ex = $(this).val().split('.').pop();
		if(ex!='jpg' && ex!='png' && ex!='gif'){
			alert('Вы загрузили файл не правильного формата. Поддерживается jpg, png, gif формат.');
			return false;
		}
		$("#popup").removeClass('hidden').addClass('allScreen');
		//starting setting some animation when the ajax starts and completes
		$.ajaxFileUpload({
			url: $(this).parents('form').attr('action'), 
			secureuri:false,
			fileElementId:'fileToUpload',
			dataType: 'json',
			success: function (data){ 
				$.ajax({
					url: '/cataloge/listPhoto?id=' + data.msg,
					dataType: "html",
					// context: $('#catalog'),
					// data: "ajax=true",
					type: "GET",
					success: function(data) {
						$('#catalog').html(data);
					}
				});
			}
		})
		return false;
	});
	// END upload images

	// Create object
	// -- change form
	var global_formNavigate = true; // Js Global Variable for onChange Flag

	$("#form_create input[type=text],#form_create input[type=textarea],#form_create input[type=password],#form_create input[type=radio],#form_create input[type=checkbox],#form_create input[type=file]").
	live('change keypress', function(event) { 
		global_formNavigate = false; 
	});
	$("#form_create input[type=submit]").live("click",function() { global_formNavigate = true; });
	window.onbeforeunload = function() { 
		if (global_formNavigate) { } 
		else 
		{ 
			return "Содержимое было изменено! \n Вы уверены, что хотите покинуть страницу без сохранения?"; 
	}};

	$('#steps_update a').live('click', function() {
		// var urlValue = $('#steps a').attr('href');
		$('.active').removeClass('active');
		$(this).children('span').addClass('active');
		var urlValue = $(this).attr('href').split('?');		
		$.ajax({
			url: '/cataloge/update?' + urlValue[1],
			dataType: "html",
			type: "POST",
			cache: false,
			success: function(data) {
				// $('.error').css('display','none');
				$.when( $('#form_object_update').html(data) )
					.done( function(){
						$('.error').css('display','none');
						$('.error').slideFadeToggle('normal');
					})
				console.log($('.error').text());
				$('select').styler();
				Custom.init();
			}
		});
		// alert(params);
		return false;
	});
	$('div#form_object_update form').live('submit',function() {
		var form = $(this);
		// alert('submit');
		$.ajax({
			'type':'POST',
			'url': form.attr('action'),
			// 'url': '/cataloge/update',
			'cache': false,
			'data': form.serialize(),
			'success': function(html){
				$("#form_object_update").html(html);
				$('select').styler();
				Custom.init();
			}
		});
		return false;
	});
	$('div#form_create form').live('submit',function() {
		var form = $(this);
		$.ajax({
			'type':'POST',
			// 'url': form.attr('action'),
			'url': '/cataloge/create',
			'cache': false,
			'data': form.serialize(),
			'success': function(html){
				$("#form_create").html(html);
				$('select').styler();
				Custom.init();
			}
		});
		return false;
	});
	
	$('a.none').live('click', function(){
		return false;
	});
	$('.chooseday').live('click', function(){
		$(this).parent().addClass('green');
		return false;
	});
	
	$('.listView').live('click', function(){
		$(this).addClass('active').next().removeClass('active');
		$('#content .list').addClass('big');
		return false;
	});
	$('.photoView').live('click', function(){
		$(this).addClass('active').prev().removeClass('active');
		$('#content .list').removeClass('big');
		return false;
	});
	$('div.radio_time input').change(function() {
		var id = $(this).parent().find('input').attr('id').substring(5,6);
		var price = $('div.price');
		price.find('span').eq(id-1).siblings('span').addClass('hidden').end().removeClass('hidden');	
	});
	$('div#comment_new form').live('submit',function() {
		var form = $(this);
		$.ajax({
			'type':'POST',
			'url': form.attr('action'),
			'cache': false,
			'data': form.serialize(),
			'success': function(html){
				form.html(html);
// $('.starsRating').rating({
// 	required: true,
// 		split: 2,
// 		// starWidth : 18,

// 		readOnly: false
// 	});
				// $("#comment_list li").first().css('display','none');
				// $("#comment_list li").first().show('slow');
				// form.find('textarea').val('');
			}
		});
		return false;
	});
	$('div#message_new form').submit(function() {
		var form = $(this);
		$.ajax({
			'type':'POST',
			'url': form.attr('action'),
			'cache': false,
			'data': form.serialize(),
			'success': function(html){
				$("#message_list").html(html);
				$(".block_holder").last().css('display','none');
				$(".block_holder").last().show('slow');
				form.find('textarea').val('');
			}
		});
		return false;
	});
	// Booked
	$('a#booked').live('click', function(){
		$.ajax({
			url: '/cataloge/checkBooked',
			type: "POST",
			data: $('#form_check_booking').serialize(),
			success: function(html) {
				$('#show_popup').html(html);
				$('div.overlay').addClass('open');
				$('div.overlay').css('display','block');
			}
		});
		return false;
	});
	$('#form_booking').live('submit',function(){
		$.ajax({
			// url: '/paypal/buy',
			url: '/cataloge/booked',
			type: "POST",
			cache: false,
			data: $('#form_booking').serialize(),
			success: function(html) {
				$('#show_popup').html(html);
				$('select').styler();
			}
		});
		return false;
	});
	// Bookmark
	$('div#bookmark a').live('click', function(){/*.click(function() {*/
		var form = $(this);
		$.ajax({
			'type':'GET',
			'url': form.attr('href'),
			'cache': false,
			'success': function(html){
				$("#bookmark").html(html)
			}
		});
		return false;
	});
	$('#delFavorites').live('click',function(){
		var link = $(this);
		$.ajax({
			'type':'GET',
			'url': $(this).attr('href'),
			'cache': false,
			'success': function(html){
				link.parent('.object').slideFadeToggle('slow');
			}
		});
		return false;
	});
	$('#Object_country_id').live('change', function() {
		var country_id = $(this).val();
		if (country_id == '') {
            $('#Object_city_id').html('<option>Select a city</option>');
            $('#Object_city_id').attr('disabled', true);
            return(false);
        }
        $('#Object_city_id').attr('disabled', true);
        $('#Object_city_id').html('<option>loading...</option>');

        var url = '/cataloge/getListCity';

        $.get(
        	url,
        	'country_id=' + country_id,
        	function(result) 
        	{
				if (result.type != 'error') 
				{
					var options = '';
					var li = '';
					$(result.cities).each(function(){
						options += '<option value="' + $(this).attr('id') + '">' + $(this).attr('name') + '</option>';
						li += '<li>' + $(this).attr('name') + '</li>';
						console.log($(this).attr('name'));
					});
					$('#Object_city_id').html('<option>Select a city</option>'+options);
					$('#Object_city_id').attr('disabled', false);
					$('#Object_city_id').next('span').remove();
					$('select').styler();
				}
				$('#Object_city_id').html('<option>Select a city</option>'+options);
				$('#Object_city_id').attr('disabled', false);
				$('#Object_city_id').next('span').remove();
				$('select').styler();
        	},
        	"json"
        );
        
	});
	// all objects (Users/view)
	$('#my_object_all').live('click',function(){
		$('.my_objects_all .object').slideFadeToggle('slow');
		// $('div.my_objects_all').slideToggle("slow");
		return false;
	});
	$('.user_photo').click(function(){
		$('.my_objects_all .object').slideFadeToggle('slow');
	});

	// all messages 
	$('#messages_all').live('click',function(){
		$('ul.messages_all').slideToggle("slow");
		return false;
	});
	// END твоя функція
	$('.home_wrapper .form_container .destination').click(function() {
		if (this.value == this.defaultValue) {
			this.value = '';
		}
	});
	$('.home_wrapper .form_container .destination').blur(function() {
		if (this.value == '') {
			this.value = this.defaultValue;
		}
	});
	$('select').styler();
	$('.message .close').live('click',function() {
		$(this).parent().slideFadeToggle('normal', function() {
			$(this).remove();
		});
	});
	$('.datePicker').datepicker();
	/*$(".home_datePicker").datepicker({
		altField : "#dateIn_home span"
	});*/
	$( "#dateIn_home .home_datePicker" ).datepicker({
		onClose: function( selectedDate ) {
		    $( "#dateOut_home .home_datePicker" ).datepicker( "option", "minDate", selectedDate );
		}
    });
    $("#dateOut_home .home_datePicker").datepicker({
		onClose : function(selectedDate) {
			$("#dateIn_home .home_datePicker").datepicker("option", "maxDate", selectedDate);
		}
	});
    $( "#dateIn_home span" ).click(function(){
    	$( "#dateIn_home .home_datePicker" ).datepicker( "show" );
    });
    $( "#dateOut_home span" ).click(function(){
    	$( "#dateOut_home .home_datePicker" ).datepicker( "show" );
    });
	var $prev_img_lnk = $('#hprev_lnk');
	var $next_img_lnk = $('#hnext_lnk');

	var $timeset = 500;

	var $size = $('#backslider li').size();

	$($next_img_lnk).click(function() {
		var $showed_slide = $('#backslider li.showed');
		var $current = $($showed_slide).index();

		if ($current < $size - 1) {
			$($showed_slide).fadeOut(
					$timeset,
					function() {
						$(this).removeClass('showed').next()
								.fadeIn($timeset, function() {
									$(this).addClass('showed');
								});
					});
		} else {
			$($showed_slide).removeClass('showed').fadeOut(
					$timeset,
					function() {
						$('#backslider li').eq(0).fadeIn(
								$timeset, function() {
									$(this).addClass('showed');
								});
					});
		}
	});
	$($prev_img_lnk).click(function() {
		var $showed_slide = $('#backslider li.showed');
		var $current = $($showed_slide).index();
		if ($current > 0) {
			$($showed_slide).fadeOut($timeset, function() {
				$(this).removeClass('showed').prev().fadeIn($timeset, function() {
					$(this).addClass('showed');
				});
			});
		} else {
			$($showed_slide).fadeOut($timeset, function() {
				$(this).removeClass('showed');
				$('#backslider li').eq($size - 1).fadeIn($timeset, function() {
					$(this).addClass('showed');
				});
			});
		}
	});
	setInterval(function() {
		var $showed_slide = $('#backslider li.showed');
		var $current = $($showed_slide).index();
		if ($current < $size - 1) {
			$($showed_slide).fadeOut($timeset, function() {
				$(this).removeClass('showed').next().fadeIn($timeset, function() {
					$(this).addClass('showed');
				});
			});
		} else {
			$($showed_slide).removeClass('showed').fadeOut($timeset, function() {
				$('#backslider li').eq(0).fadeIn($timeset, function() {
					$(this).addClass('showed');
				});
			});
		}
	}, 5000);

	$('.similar_box').jScrollPane();
	$('.tabs li:not(.open)').live('click', function() {
		tab_num = $(this).index();
		$(this).parent().children('.open').removeClass('open');
		$(this).addClass('open');
		$(this).parent().next('.tab_container').children('.open').removeClass('open').hide(0);
		$(this).parent().next('.tab_container').children().eq(tab_num).addClass('open').show(0);
	});
	$('.inp_col .inp_text input[type="text"]').focus(function() {
		$(this).addClass('focused');
	});
	$('.inp_col .inp_text input[type="text"]').blur(function() {
		$(this).removeClass('focused');
	});
	$('.openmaps').live('click', function(){
		if(!$('#map_canvas').hasClass('done')){
			var address = $('#map_canvas').html();
			$('#map_canvas').addClass('done').html('').show(0);
			initMap(address);
		}
	});
	$('.openstreetview').live('click', function(){
		if(!$('#map_streetview').hasClass('done')){
			var address = $('#map_streetview').html();
			$('#map_streetview').addClass('done').html('').show(0);
			initMapStreeView(address);
		}
	});
	$('.showMap').live('click', function(){
		$('#map_canvas').show(0).appendTo($('.overlay .popup'));
		$('.overlay').show(0).addClass('map');
		var crntAddress = $(this).attr('title');
		var addresses = window.addresses;
		var crnt = $.inArray(crntAddress, addresses);
		initBigMap(addresses, crnt);
	});
	/*------------------ SLIDER ---*/
	var slider_li_w = $('#slider li').width();
	var slider_size = $('#slider li').size();
	var slider_width = slider_li_w * slider_size;
	var maxleft = slider_size * slider_li_w;

	$('#slider').css({
		position : 'absolute',
		left : 0,
		width : slider_width
	});

	$('.slider_container .next').click(function() {
		var slider = $('#slider');
		if(slider.hasClass('ready')){
			var slider_pos = slider.position();
			var slider_pos_left = slider_pos.left;
			var new_pos = slider_pos_left - slider_li_w;
			if (new_pos > -slider_width) {
				slider.removeClass('ready');
				slider.animate({
					left : new_pos
				}, 400, function() {
					slider.addClass('ready');
				});
				var current_thumb = $('#slider_thumbs li.current').index();
				$('#slider_thumbs li.current').removeClass('current');
				$('#slider_thumbs li').eq(current_thumb + 1).addClass('current');
			}
		}
		return false;
	});

	$('.slider_container .prev').click(function() {
		var slider = $('#slider');
		var slider_pos = slider.position();
		var slider_pos_left = slider_pos.left+1;
		var new_pos = slider_pos_left + slider_li_w;

		if (new_pos <= 0) {
			$('#slider').animate({
				left : new_pos
			}, 400);
		} else return;

		var current_thumb = $('#slider_thumbs li.current').index();
		$('#slider_thumbs li.current').removeClass('current');
		$('#slider_thumbs li').eq(current_thumb - 1).addClass('current');
	});

	$('#slider_thumbs li').click(function() {
		var slider = $('#slider');
		if(slider.hasClass('ready')){
			slider.removeClass('ready');
			$('#slider_thumbs li').removeClass('current');
			$(this).addClass('current');
			var num = $(this).index();
			var current_slide = -(slider_li_w * num);
			slider.animate({
				left : current_slide
			}, 400, function() {
				slider.addClass('ready');
			});
		}
		return false;
	});
	/*----------------------*/

	$('.descr_table table tr:even').addClass('line');

	var window_height = $(document).height();
	var window_width = $(document).width();
	$('.overlay').css({
		height : window_height,
		width : window_width
	});

	$('.popup .close_btn').click(function() {
		$(this).parent().parent('.overlay').fadeOut(300, function() {
			$(this).removeClass('open');
		});
	});
});
$(function() {
	if (window.PIE) {
		$('.container,.br7, .br5, .br3,#rent_btn, .home_wrapper article,footer,#sub_nav li,.btn, textarea').each(function() {
			PIE.attach(this);
		});
	}
});
$(window).resize(function() {
	var window_height = $(document).height();
	var window_width = $(document).width();
	$('.overlay').css({
		height : window_height,
		width : window_width
	});
});
